<script setup>
import router from '@/router';
import { onMounted, ref, nextTick } from 'vue';
import { ElMessageBox, ElMessage, ElForm, ElFormItem, ElInput, ElDatePicker, ElSelect, ElOption, ElTree } from 'element-plus'
import QRCode from 'qrcode'
import {useNavStore} from "@/stores/nav.js";


const navStore = useNavStore()
// 表格数据
const tableData = ref([
  {
    title: '标题1',
    scaleNum: 5,
    progress: 10,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题1',
    scaleNum: 5,
    progress: 20,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题2',
    scaleNum: 5,
    progress: 40,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题2',
    scaleNum: 5,
    progress: 80,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题3',
    scaleNum: 5,
    progress: 50,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题3',
    scaleNum: 5,
    progress: 60,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题3',
    scaleNum: 5,
    progress: 90,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题4',
    scaleNum: 5,
    progress: 100,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题4',
    scaleNum: 5,
    progress: 5,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题5',
    scaleNum: 5,
    progress: 40,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题6',
    scaleNum: 5,
    progress: 60,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题7',
    scaleNum: 5,
    progress: 70,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题8',
    scaleNum: 5,
    progress: 80,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题9',
    scaleNum: 5,
    progress: 80,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
  {
    title: '标题10',
    scaleNum: 5,
    progress: 80,
    arrangeGroupTest: 0,
    evaTime: '2025-09-19 12:45:12',
    addUser: '张三',
    updateTime: '2025-09-19 12:45:12',
  },
])
// 表格数据的复制品
const tableDataCopy = ref([])
// 当前页数据
const currentTableData = ref([])
// 当前页
const currentPage = ref(1)
// 当前页大小
const currentPageSize = ref(10)
// 搜索信息
const searchInfo = ref({ title: '', date: [] })
// 控制二维码弹窗是否显示
const qrDialogVisible = ref(false)
// 当前要展示的链接
const currentLink = ref('')
// canvas 用于渲染二维码（模板中用 ref 绑定）
const qrCanvasRef = ref()

// 控制添加团测弹窗是否显示
const addDialogVisible = ref(false)
// 添加团测表单数据
const addGroupTestForm = ref({
  title: '', // 团测标题
  evaTime: '', // 测评时间
  selectedScales: [], // 选择的量表
  school: '', // 学校
  major: '', // 专业
  class: '' // 班级
})

// 可选量表列表 - 分为8大类
const availableScales = ref([
  // 1.1 心理健康
  { value: 'sds', label: '抑郁自评量表（SDS）', group: '1.1 心理健康' },
  { value: 'sas', label: '焦虑自评量表（SAS）', group: '1.1 心理健康' },
  { value: 'asles', label: '青少年生活事件量表', group: '1.1 心理健康' },
  { value: 'scl90', label: 'SCL-90症状自评量表', group: '1.1 心理健康' },
  { value: 'dass21', label: '情绪自评量表（DASS-21）', group: '1.1 心理健康' },
  { value: 'adolescentSex', label: '青春期性心理健康量表', group: '1.1 心理健康' },
  
  // 1.2 职业选择
  { value: 'mbti', label: 'MBTI性格类型测试问卷', group: '1.2 职业选择' },
  { value: 'holland', label: '霍兰德职业倾向测验量表', group: '1.2 职业选择' },
  
  // 1.3 学习心理
  { value: 'cognitiveFlex', label: '认知灵活性问卷', group: '1.3 学习心理' },
  { value: 'flowInLearning', label: '学习沉醉感量表', group: '1.3 学习心理' },
  { value: 'timeMgmt', label: '时间管理自我监控量表', group: '1.3 学习心理' },
  { value: 'creativity', label: '创造性倾向问卷', group: '1.3 学习心理' },
  { value: 'examPsych', label: '考试心理和行为问题症状自评量表', group: '1.3 学习心理' },
  { value: 'burnout', label: '学习倦怠量表', group: '1.3 学习心理' },
  
  // 1.4 学校文化
  { value: 'teacherStudent', label: '师生关系量表', group: '1.4 学校文化' },
  { value: 'lifeSatisfaction', label: '青少年学生生活满意度量表', group: '1.4 学校文化' },
  
  // 1.5 恋爱关系
  { value: 'loveStress', label: '恋爱心理压力源量表', group: '1.5 恋爱关系' },
  { value: 'sternbergLove', label: '斯腾伯格爱情量表', group: '1.5 恋爱关系' },
  
  // 1.6 人格特质
  { value: 'resilience', label: '心理韧性量表', group: '1.6 人格特质' },
  { value: 'selfIdentity', label: '自我认同感量表', group: '1.6 人格特质' },
  { value: 'bigFive', label: '大五人格量表简化版', group: '1.6 人格特质' },
  { value: 'epq', label: '艾森克人格问卷（EPQ）', group: '1.6 人格特质' },
  { value: 'eq', label: '情商测试量表', group: '1.6 人格特质' },
  { value: '16pf', label: '卡特尔16种性格因素人格测验', group: '1.6 人格特质' },
  { value: 'rosenberg', label: 'Rosenberg自尊量表', group: '1.6 人格特质' },
  
  // 1.7 家庭关系
  { value: 'familyCohesion', label: '家庭亲合量表', group: '1.7 家庭关系' },
  { value: 'socialSupport', label: '社会支持评定量表', group: '1.7 家庭关系' },
  { value: 'parentingStyle', label: '父母教养方式问卷', group: '1.7 家庭关系' },
  { value: 'filialPiety', label: '双元孝道信念量表', group: '1.7 家庭关系' },
  
  // 1.8 人际关系
  { value: 'interpersonal', label: '人际关系综合诊断量表', group: '1.8 人际关系' },
  { value: 'socialAnxiety', label: '社交焦虑量表', group: '1.8 人际关系' },
  { value: 'interpersonalTrust', label: '人际信任量表（ITS）', group: '1.8 人际关系' }
])

// 按group属性将量表数据分组
const getGroupedScales = () => {
  const groups = {}
  
  // 遍历所有量表，按group属性分组
  availableScales.value.forEach(scale => {
    if (!groups[scale.group]) {
      groups[scale.group] = []
    }
    groups[scale.group].push(scale)
  })
  
  // 转换为分组格式
  return Object.keys(groups).map(groupName => ({
    label: groupName,
    options: groups[groupName]
  }))
}

// 学校结构数据 - 河南工业和信息化职业学院的四级结构
const schoolData = ref([
  {
    label: '河南工业和信息化职业学院',
    children: [
      {
        label: '计算机应用技术',
        children: [
          {
            label: '2025级',
            children: [
              { label: '1班' },
              { label: '2班' },
              { label: '3班' },
            ],
          },
          {
            label: '2024级',
            children: [
              { label: '1班' },
              { label: '2班' },
              { label: '3班' },
            ],
          },
          {
            label: '2023级',
            children: [
              { label: '1班' },
              { label: '2班' },
              { label: '3班' },
            ],
          },
          {
            label: '2022级',
            children: [
              { label: '1班' },
              { label: '2班' },
              { label: '3班' },
            ],
          },
        ],
      },
    ],
  }
])

// 班级选择相关变量
const selectedClassNode = ref(null) // 当前选中的班级节点
const classSelectionDialogVisible = ref(false) // 班级选择对话框显示状态
const classInfo = ref({ // 选中的班级信息
  school: '',
  major: '',
  class: ''
})
// 添加团测表单验证规则
const addGroupTestRules = ref({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 1, max: 50, message: '标题长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  evaTime: [
    { required: true, message: '请选择测评时间', trigger: 'change' }
  ],
  school: [
    { required: true, message: '请选择学校', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请选择专业', trigger: 'blur' }
  ],
  class: [
    { required: true, message: '请选择班级', trigger: 'blur' }
  ],
  selectedScales: [
    { 
      required: true, 
      message: '请至少选择一个量表', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (value && value.length > 0) {
          callback()
        } else {
          callback(new Error('请至少选择一个量表'))
        }
      }
    }
  ]
})
// 添加团测表单引用
const addGroupTestFormRef = ref(null)
// 页大小改变
const handleSizeChange = (newPageSize) => {
  currentTableData.value = tableData.value.slice(0, newPageSize)
}
// 改变页
const handleCurrentChange = (newPage) => {
  const start = (newPage - 1) * currentPageSize.value
  const end = start + currentPageSize.value
  currentTableData.value = tableData.value.slice(start, end)
}
// 搜索
const search = () => {
    tableData.value = []
    for (let index = 0; index < tableDataCopy.value.length; index++) {
      if (searchInfo.value.title && searchInfo.value.title != tableDataCopy.value[index].title) continue
      if (searchInfo.value.date && searchInfo.value.date.length != 0 && (tableDataCopy.value[index].evaTime < searchInfo.value.date[0] ||  tableDataCopy.value[index].evaTime > searchInfo.value.date[1])) continue
      tableData.value.push(tableDataCopy.value[index])
    }
    currentPage.value = 1
    currentTableData.value = tableData.value.slice(0, currentPageSize.value)
}
// 重置
const reset = () => {
  searchInfo.value = { title: '', date: [] }
  tableData.value = tableDataCopy.value
  currentTableData.value = tableData.value.slice(0, currentPageSize.value)
}
// 获取进度条状态
const getProgressStatus = (progress) => {
    if (progress >= 100) return 'success'
    if (progress >= 20 && progress < 100) return 'warning'
    else return 'exception'
}
// 展示二维码
const showMa = (row) => {
  // 假设你的团测链接规则是：https://yourdomain.com/group-test?title=标题&id=xxx
  // 这里你可以根据实际业务拼接 URL
  const baseUrl = 'https://example.com/group-test'
  const link = `${baseUrl}?title=${encodeURIComponent(row.title)}&id=${row.id || Date.now()}`

  currentLink.value = link
  qrDialogVisible.value = true

  // 使用 nextTick 确保 dialog 渲染完成后再绘制二维码
  nextTick(() => {
    if (qrCanvasRef.value) {
      QRCode.toCanvas(qrCanvasRef.value, link, {
        width: 200,
        height: 200,
        margin: 2,
        color: {
          dark: '#000000',
          light: '#ffffff'
        }
      }, (error) => {
        if (error) console.error('生成二维码失败:', error)
      })
    }
  })
}
// 删除团测
const del = (row, index) => {
  ElMessageBox.confirm(
      `确定要删除标题为 "${row.title}" 的团测吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
        const pageIndex = (currentPage.value - 1) * currentPageSize.value + index
        tableData.value.splice(pageIndex, 1)
        tableDataCopy.value = [...tableData.value] // 保持副本同步
        handleCurrentChange(currentPage.value) // 重新加载当前页数据

        ElMessage({ type: 'success', message: '删除成功' })
      })
      .catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' })
      })
}

// 打开添加团测对话框
const openAddDialog = () => {
  // 重置表单
  if (addGroupTestFormRef.value) {
    addGroupTestFormRef.value.resetFields()
  }
  // 设置默认测评时间为当前时间
  const now = new Date()
  const formattedDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
  addGroupTestForm.value.evaTime = formattedDate
  
  addDialogVisible.value = true
}

// 提交添加团测表单
const submitAddGroupTest = () => {
  if (!addGroupTestFormRef.value) return
  
  addGroupTestFormRef.value.validate((valid) => {
    if (valid) {
      // 构造新的团测数据
      const newGroupTest = {
        title: addGroupTestForm.value.title,
        scaleNum: addGroupTestForm.value.selectedScales.length, // 量表数从选中的量表数组长度计算得出
        progress: 0, // 新建时进度为0
        arrangeGroupTest: 0,
        evaTime: addGroupTestForm.value.evaTime,
        addUser: '张三', // 假设当前用户为张三，实际应从登录信息获取
        updateTime: addGroupTestForm.value.evaTime, // 创建时间即为更新时间
        school: addGroupTestForm.value.school,
        major: addGroupTestForm.value.major,
        class: addGroupTestForm.value.class
      }
      
      // 添加到数据列表
      tableData.value.unshift(newGroupTest) // 插入到列表开头
      tableDataCopy.value = [...tableData.value] // 更新副本
      
      // 重新加载当前页数据
      handleCurrentChange(currentPage.value)
      
      // 关闭对话框
      addDialogVisible.value = false
      
      // 显示成功提示
      ElMessage({ type: 'success', message: '添加团测成功' })
    } else {
      ElMessage({ type: 'error', message: '表单验证失败，请检查输入' })
      return false
    }
  })
}

// 重置添加团测表单
const resetAddForm = () => {
  addGroupTestForm.value = {
    title: '',
    evaTime: '',
    selectedScales: [],
    school: '',
    major: '',
    class: ''
  }
  if (addGroupTestFormRef.value) {
    addGroupTestFormRef.value.resetFields()
  }
  // 重置班级选择信息
  classInfo.value = {
    school: '',
    major: '',
    class: ''
  }
  selectedClassNode.value = null
}

// 打开班级选择对话框
const openClassSelectionDialog = () => {
  classSelectionDialogVisible.value = true
}

// 处理班级树节点点击
const handleClassNodeClick = (data, node) => {
  // 只有当点击的是班级节点（没有子节点）时才选择
  if (!data.children) {
    selectedClassNode.value = data
    // 获取父节点信息（专业）
    const parentNode = node.parent
    if (parentNode) {
      classInfo.value = {
        school: parentNode.parent.label,
        major: parentNode.label,
        class: data.label
      }
    }
  }
}

// 确认选择班级
const confirmClassSelection = () => {
  if (selectedClassNode.value && classInfo.value.school && classInfo.value.major && classInfo.value.class) {
    addGroupTestForm.value.school = classInfo.value.school
    addGroupTestForm.value.major = classInfo.value.major
    addGroupTestForm.value.class = classInfo.value.class
    classSelectionDialogVisible.value = false
  } else {
    ElMessage.warning('请先选择一个班级')
  }
}

// 处理班级选择对话框关闭
const handleClassDialogClose = () => {
  classSelectionDialogVisible.value = false
}

// 前往完成情况
const goToFinshInfo = () => {
  navStore.addNav({name: '完成情况', path: '/finshinfo'})
  router.push({ path: '/finshinfo' })
}
// 前往编辑计划
const goToEditPlan = () => {
  navStore.addNav({name: '编辑计划', path: '/evaluation/editplan'})
  router.push('/evaluation/editplan')
}
onMounted(() => {
  tableDataCopy.value = tableData.value
  currentTableData.value = tableData.value.slice(0, currentPageSize.value)
})
</script>

<template>
<!-- 搜索部分 -->
<div class="search-box">
  <!-- {{ '2025' }} -->
    <el-row>
        <el-col :span="9">
            <el-button type="primary" @click="openAddDialog"><el-icon><Plus /></el-icon>&nbsp;添加</el-button>
        </el-col>
        <el-col :span="5">
            <el-input v-model.trim="searchInfo.title" style="width: 240px" placeholder="请输入标题" />
        </el-col>
        <el-col :span="7">
            <el-date-picker
                v-model="searchInfo.date"
                type="daterange"
                range-separator="-"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            />
        </el-col>
        <el-col :span="3">
            <el-button type="primary" @click="search">查询</el-button>
            <el-button type="primary" @click="reset">重置</el-button>
        </el-col>
    </el-row>
</div>
<!-- 表格部分 -->
<div class="table-box">
    <el-table :data="currentTableData" style="width: 100%" height="450px" :header-cell-style="{ 'background-color': '#f5f7fa' }">
        <el-table-column fixed prop="title" label="标题" min-width="150" />
        <el-table-column prop="scaleNum" label="量表数" min-width="100" />
        <el-table-column prop="progress" label="进度" min-width="180">
            <template #default="scope">
                <el-progress :percentage="scope.row.progress" :status="getProgressStatus(scope.row.progress)"/>
            </template>
        </el-table-column>
        <el-table-column prop="arrangeGroupTest" label="分发团测" min-width="120">
            <template #default="scope">
              <el-link type="primary" @click="showMa(scope.row)">链接和二维码</el-link>
            </template>
        </el-table-column>
        <!-- <el-table-column prop="school" label="班级信息" min-width="180">
            <template #default="scope">
              <div v-if="scope.row.school && scope.row.major && scope.row.class">
                {{ scope.row.school }} - {{ scope.row.major }} - {{ scope.row.class }}
              </div>
              <div v-else>
                - 
              </div>
            </template>
        </el-table-column> -->
        <el-table-column prop="evaTime" label="测评时间" min-width="180" />
        <el-table-column prop="addUser" label="添加者" min-width="180" />
        <el-table-column prop="updateTime" label="操作时间" min-width="180" />
        <el-table-column fixed="right" label="操作" min-width="180">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="goToFinshInfo()">完成情况</el-button>
              <el-button link type="primary" size="small" @click="goToEditPlan()">编辑</el-button>
              <el-button link type="danger" size="small" @click="del(scope.row, scope.$index)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
</div>
<!-- 分页部分 -->
<div class="page-box">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="currentPageSize"
        :page-sizes="[10, 20, 30, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
</div>
  <!-- 二维码弹窗 -->
  <el-dialog v-model="qrDialogVisible" title="链接和二维码" width="350px" center>
    <div style="text-align: center;">
      <p><strong>访问链接：</strong></p>
      <el-input v-model="currentLink" size="small" readonly style="margin-bottom: 15px;" />
      <canvas ref="qrCanvasRef"></canvas>
      <p style="color: #999; font-size: 12px; margin-top: 10px;">扫码参与测评</p>
    </div>
    <template #footer>
      <div style="text-align: center;">
        <el-button @click="qrDialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
  
  <!-- 添加团测弹窗 -->
  <el-dialog v-model="addDialogVisible" title="添加团测" width="500px" center>
    <el-form ref="addGroupTestFormRef" :model="addGroupTestForm" :rules="addGroupTestRules" label-width="100px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="addGroupTestForm.title" placeholder="请输入标题" maxlength="50" show-word-limit />
      </el-form-item>
      <el-form-item label="测评时间" prop="evaTime">
        <el-date-picker
          v-model="addGroupTestForm.evaTime"
          type="datetime"
          placeholder="选择日期时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="班级信息" prop="school">
        <div style="display: flex; align-items: center;">
          <span style="flex: 1; text-align: left;">
            {{ addGroupTestForm.school }} - {{ addGroupTestForm.major }} - {{ addGroupTestForm.class }}
          </span>
          <el-button type="primary" size="small" @click="openClassSelectionDialog">
            选择班级
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="选择量表" prop="selectedScales">
        <el-select
          v-model="addGroupTestForm.selectedScales"
          multiple
          filterable
          allow-create
          placeholder="请选择量表"
          style="width: 100%;"
          popper-class="grouped-select-popper"
          collapse-tags
        >
          <template v-for="group in getGroupedScales()" :key="group.label">
            <el-option-group :label="group.label">
              <el-option
                v-for="scale in group.options"
                :key="scale.value"
                :label="scale.label"
                :value="scale.value"
              />
            </el-option-group>
          </template>
        </el-select>
        <div style="color: #909399; font-size: 12px; margin-top: 8px;">
          已选择 {{ addGroupTestForm.selectedScales.length }} 个量表
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center;">
        <el-button @click="resetAddForm">重置</el-button>
        <el-button type="primary" @click="submitAddGroupTest">确定</el-button>
        <el-button @click="addDialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
  
  <!-- 班级选择对话框 -->
  <el-dialog
    v-model="classSelectionDialogVisible"
    title="选择班级"
    width="500px"
  >
    <el-tree
      :data="schoolData"
      :default-expand-all="true"
      @node-click="handleClassNodeClick"
      highlight-current
      ref="tree"
    >
      <template #default="{ node, data }">
        <span :class="{ 'text-primary': selectedClassNode && selectedClassNode.label === data.label }">
          {{ data.label }}
        </span>
      </template>
    </el-tree>
    
    <template #footer>
      <el-button @click="classSelectionDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmClassSelection">确认选择</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.search-box {
    padding: 10px 0px 10px 10px;
}
.table-box {
    padding-left: 10px;
}
.page-box {
    display: flex;
    justify-content: center;
    padding-top: 10px;
}
</style>
 
